import { reactive, watch } from 'vue'
const userInfo = localStorage.getItem('user_info');
const configUrl = new URL('/config.json', import.meta.url).href
const tjUrl = new URL('/tuijian.json', import.meta.url).href
const dxUrl = new URL('/dianxin.json', import.meta.url).href
const ltUrl = new URL('/liantong.json', import.meta.url).href
const ydUrl = new URL('/yidong.json', import.meta.url).href
const state = reactive({
  keyword: '',
  config: '',
  tjData: [],
  dxData: [],
  ltData: [],
  ydData: [],
  searchData: null,
  userInfo: userInfo,
  list: null
})
watch(() => state.userInfo, (data) => {
  if(data && typeof data === 'object') {
    localStorage.setItem('user_info', JSON.stringify(data))
  } else {
    localStorage.setItem('user_info', data)
  }
}, {
  deep: true
})
export function useState() {
  function getAllJSON() {
    tjUrl && !state.config && fetch(tjUrl).then(response => response.json()).then(data => {
      state.tjData = data
    })
    configUrl && !state.config && fetch(configUrl).then(response => response.json()).then(data => {
      state.config = data
    })
    dxUrl && !state.dxData.length && fetch(dxUrl).then(response => response.json()).then(data => {
      state.dxData = data
    })
    ltUrl && !state.ltData.length && fetch(ltUrl).then(response => response.json()).then(data => {
      state.ltData = data
    })
    ydUrl && !state.ydData.length && fetch(ydUrl).then(response => response.json()).then(data => {
      state.ydData = data
    })
  }

  function onSearch(keyword) {
    state.searchData = []
    const data = [...state.dxData, ...state.ltData, ...state.ydData]
    data.forEach((item) => {
      if(item.parent_title.indexOf(keyword) !== -1) {
        state.searchData.push(item)
      }
    })
  }

  function onClear() {
    state.searchData = null
  }

  getAllJSON()
  return {
    state,
    onSearch,
    onClear
  }
}
